package com.parkinginfo.manager;

/*
 * Author: Deepika Gohil
 */

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;

import android.os.Bundle;
import com.google.android.maps.MapView.LayoutParams;  

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.graphics.drawable.Drawable;
import android.location.Geocoder;

import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;

import com.google.android.maps.OverlayItem;
import com.parkinginfo.dbhelper.Place;
import com.parkinginfo.manager.ParkingManagerApplication;

public class SimpleMapsActivity extends MapActivity {
	  private MapView mapView;
	  private EditText locationtext;
	  private Button mapLocationButton;
	  private Button useLocationButton;
	  private Geocoder gc;
	  private double lat;
	  private double lon;
	  private AlertDialog unsavedChangesDialog;
	  
	  private boolean locPending = true;
	
	  
	 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.add_location);
 
        setUpViews();
    }
 
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
    private void setUpViews() 
    {
    	gc = new Geocoder(this); 
        mapView = (MapView) findViewById(R.id.mapView);
        LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);  
        View zoomView = mapView.getZoomControls(); 
 
        zoomLayout.addView(zoomView, 
            new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, 
                LayoutParams.WRAP_CONTENT)); 
        mapView.displayZoomControls(true);
        
        locationtext = (EditText)findViewById(R.id.loc_name);
		mapLocationButton = (Button)findViewById(R.id.maploc_button);
		useLocationButton = (Button)findViewById(R.id.use_location);
		
		mapLocationButton.setOnClickListener(new View.OnClickListener() {
		      public void onClick(View v) {
		    	  locPending = true;
		          String addressInput = locationtext.getText().toString(); //Get input text	
		          try {
		  					
		            List<Address> foundAdresses = gc.getFromLocationName(addressInput, 5); //Search addresses
		  					
		            if (foundAdresses.size() == 0) { 
		             // if the address entered is not found, show dialog!
		              Dialog locationError = new AlertDialog.Builder(SimpleMapsActivity.this)
		                .setIcon(0)
		                .setTitle("Error")
		                .setPositiveButton(R.string.ok, null)
		                .setMessage("Sorry, the address doesn't exist!")
		                .create();
		              locationError.show(); 
		            }
		            else { 
		               locPending = false;
		              //else show address on the map!
		              for (int i = 0; i < foundAdresses.size(); ++i) {
		                Address x = foundAdresses.get(i);
		                lat = x.getLatitude();
		                lon = x.getLongitude();
		              }
		            //navigate to address on the map using longitude and latitude
		            navigatetoAddress((lat * 1000000), (lon * 1000000)); 
		            }
		          }
		          catch (Exception e) {
		            //@todo: Show error message
		          }	
		        }
		      });
		
		//add lisner to use location
		useLocationButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (locPending) {
					unsavedChangesDialog = new AlertDialog.Builder(SimpleMapsActivity.this)
					    .setTitle("Error")
						.setMessage("Location not selected. Do you want to add location?")
						.setPositiveButton("Add Location", new AlertDialog.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								
							}
						})
						.setNeutralButton(R.string.no, new AlertDialog.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						})
						.setNegativeButton(android.R.string.cancel, new AlertDialog.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								
							}
						})
						.create();
					unsavedChangesDialog.show();
				} else {
					//send location to the component.
					finishAndSend();
				}
			}
		});
		
		}
    
    //send data back to the callactivity
    public void finishAndSend() {
    	// Prepare data intent 
    	Intent data = new Intent();

    	Place p = new Place(locationtext.getText().toString());
    	p.setLocation(locationtext.getText().toString());
    	p.setLattitude(lat);
    	p.setLongitude(lon);
    	
    	((ParkingManagerApplication)getApplication()).addPlace(p);
    	
    	super.finish();
    }
    
    //create marker on the map
	 private void createMarker(GeoPoint p) 
	    {
		 List<Overlay> mapOverlays = mapView.getOverlays();
		 Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
		 MyOverLays itemizedoverlay = new MyOverLays(drawable, this);
		 OverlayItem overlayitem = new OverlayItem(p, "You have selected:", locationtext.getText().toString());
		 itemizedoverlay.addOverlay(overlayitem);
		 mapOverlays.add(itemizedoverlay);
		}
		      
	 // Navigates a given MapView to the specified Longitude and Latitude
	 private void navigatetoAddress(double latitude, double longitude) 
	    {
		      GeoPoint p = new GeoPoint((int) latitude, (int) longitude); 
		      mapView.displayZoomControls(true); 
		      MapController mc = mapView.getController();
		      mc.animateTo(p);
		      int zoomlevel = mapView.getMaxZoomLevel(); 
		      mc.setZoom(zoomlevel - 3);
		      mapView.setSatellite(false);
		      
		      createMarker(p);
		      mapView.invalidate();
		}
}